import { CloseOutlined } from '@ant-design/icons';
import { Drawer } from 'antd';
import React, { useMemo, useState } from 'react';
import { Form } from '../../configComponent';
import { Button } from '../../functionalComponent';
import { Layout, registerComponent, iup, useApi, type IObject } from '../../util';
import { Grid } from '../grid';
import { opFormColumns, opFormConfig } from './constVar';
import { exportTemplate, getByBizCode } from './services';

const { Flex } = Layout;
interface props {
  state: IObject;
  setState: Function;
}

export const DownloadExcel: React.FC<props> = ({ state }) => {
  const { keyCode } = state;
  const formRef = useApi();
  const gridRef = useApi();

  const [value, setValue] = useState<IObject>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [showModal, setShowModal] = useState<boolean>(false);

  const request = useMemo(
    () => async () => {
      if (showModal && keyCode) {
        const rc = await getByBizCode({ bizCode: keyCode });
        setValue({ ...rc.data });
        return (rc.data?.dtlList || []).map((it) => ({ ...it, init: it.mustInput }));
      }
      return [];
    },
    [showModal]
  );

  const save = async () => {
    const tableData = gridRef.current.getApi().getData();
    if (!gridRef.current.getApi().validData?.()) {
      iup.alert('保存失败,请检查必填项是否填写!');
      return;
    }
    setLoading(true);
    const rc: any = await exportTemplate({
      fileName: 'excel',
      idList: tableData.filter((it) => it.mustInput).map((it) => it.id)
    });
    setLoading(false);
    if (rc?.message) {
      iup.alert(rc.message);
    } else {
      iup.downLoad({
        blob: base64toBlob(rc),
        filename: '导入.xls'
      });
      iup.alert('导出成功');
      setShowModal(false);
    }
  };

  const base64toBlob = (base64: string) => {
    // 将base64转为Unicode规则编码
    const bstr = window.atob(base64);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n); // 转换编码后才可以使用charCodeAt 找到Unicode编码
    }
    return new Blob([u8arr], { type: 'application/vnd.ms-excel' });
  };

  const close = () => {
    setShowModal(false);
  };
  return (
    <>
      <Button onClick={() => setShowModal(true)} key="edit">
        模版编辑
      </Button>
      <Drawer
        title={'模版编辑'}
        width={700}
        closable={false}
        onClose={close}
        open={showModal}
        destroyOnClose
        zIndex={995}
        extra={<CloseOutlined onClick={close} />}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button style={{ marginRight: 10 }} onClick={close}>
              取消
            </Button>
            <Button type="primary" onClick={save} loading={loading}>
              模版导出
            </Button>
          </div>
        }
      >
        <Layout>
          <Form id="excelModel" ref={formRef} colspan={2} value={value} config={opFormConfig} disabled />
          <Flex>
            <Grid
              busKey="id"
              ref={gridRef}
              bordered
              editColumnIcon
              headerMenu={false}
              showRowNumber
              columns={opFormColumns}
              request={request}
            />
          </Flex>
        </Layout>
      </Drawer>
    </>
  );
};

registerComponent({ DownloadExcel });
